In object-oriented programming with classes, a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist.[1][2][3][4]
A class variable is the opposite of an instance variable. It is a special type of class attribute (or class property, field, or data member).
In Java, C#, and C++, class variables are declared with the keyword static
, and may therefore be referred to as static member variables.
The same dichotomy between instance and class members applies to methods ("member functions") as well; a class may have both instance methods and class methods. Again, Java, C#, and C++ use the keyword static
to indicate that a method is a class method ("static member function").
struct Request { static int count; int number; Request() { number = count; // modifies the instance variable "this->number" ++count; // modifies the class variable "Request::count" } }; int Request::count = 0;
In this C++ example, the class variable Request::count
is incremented on each call to the constructor, so that Request::count
always holds the number of Requests that have been constructed, and each new Request object is given a number
in sequential order. Since count
is a class variable, there is only one object Request::count
; in contrast, each Request object contains its own distinct number
field.